package com.gzx.plugin.tjzy.modular.debtor.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fhs.trans.service.impl.TransService;
import com.google.common.collect.Lists;
import com.gzx.plugin.tjzy.modular.debtor.entity.GzxDebtorInfo;
import com.gzx.plugin.tjzy.modular.debtor.entity.bo.GzxDebtorInfoEditBo;
import com.gzx.plugin.tjzy.modular.debtor.entity.vo.GzxDebtorInfoVo;
import com.gzx.plugin.tjzy.modular.debtor.mapper.GzxDebtorInfoMapper;
import com.gzx.plugin.tjzy.modular.debtor.service.GzxDebtorInfoService;
import com.gzx.plugin.tjzy.modular.gzxcase.mapper.GzxCaseMapper;
import com.gzx.plugin.tjzy.modular.gzxcase.vo.GzxCaseVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2024/12/4 09:26
 */
@Service
@RequiredArgsConstructor
@DS("tjzy")
public class GzxDebtorInfoServiceImpl implements GzxDebtorInfoService {

    private final GzxDebtorInfoMapper debtorInfoMapper;

    private final GzxCaseMapper caseMapper;

    private final TransService transService;

    /**
     * 根据案件ID查询欠款人数据
     *
     * @param caseId
     * @return
     */
    @Override
    public List<GzxDebtorInfoVo> getDebtorByCaseId(Long caseId) {
        GzxCaseVo caseVo = caseMapper.selectVoById(caseId);
        if (caseVo == null) {
            throw new CommonException("无案件信息");
        }
        GzxDebtorInfo debtorInfo = debtorInfoMapper.selectOne(new LambdaQueryWrapper<GzxDebtorInfo>()
                .eq(GzxDebtorInfo::getDebtorCardId, CommonCryptogramUtil.doSm1AesEncrypt(caseVo.getDebtorCardId()))
                .eq(GzxDebtorInfo::getProjectCode, caseVo.getProjectCode()));
        if (debtorInfo == null) {
            throw new CommonException("无欠款人信息");
        }
        List<GzxDebtorInfoVo> debtorInfoVoList = new ArrayList<>();
        transService.transOne(caseVo);
        transService.transOne(debtorInfo);
        debtorInfoVoList.add(new GzxDebtorInfoVo("客户ID:", debtorInfo.getDebtorName(), "案件类型:", caseVo.getProjectName(), "意向等级:", caseVo.getIntentTagName()));
        debtorInfoVoList.add(new GzxDebtorInfoVo("逾期状态:", "是", "年龄:", String.valueOf(debtorInfo.getDebtorAge()), "身份证号:", CommonSensitiveUtil.sensitiveIdCard(debtorInfo.getDebtorCardId())));
        debtorInfoVoList.add(new GzxDebtorInfoVo("借款总金额:", String.valueOf(caseVo.getLoanAmount()), "性别:", debtorInfo.getDebtorSexName(), "甲方主键:", caseVo.getPartnerBusinessId()));
        debtorInfoVoList.add(new GzxDebtorInfoVo("逾期总金额:", String.valueOf(caseVo.getOverdueAmount()), "逾期天数:", "未知", "户籍地址:", StringUtils.isNotBlank(debtorInfo.getDebtorAddress()) ? CommonSensitiveUtil.sensitiveString(debtorInfo.getDebtorAddress(), 4, debtorInfo.getDebtorAddress().length() - 5) : null));
        debtorInfoVoList.add(new GzxDebtorInfoVo("应催总金额:", String.valueOf(caseVo.getCleanLoanAmount()), "手机号:", CommonSensitiveUtil.sensitivePhone(caseVo.getDebtorPhone()), "预留地址:", StringUtils.isNotBlank(debtorInfo.getDebtorNowAddress()) ? CommonSensitiveUtil.sensitiveString(debtorInfo.getDebtorNowAddress(), 4, debtorInfo.getDebtorNowAddress().length() - 5) : null));
        Map<String, Object> map = new HashMap<>();
        map.put("debtorId", debtorInfo.getId());
        map.put("debtorCardId", debtorInfo.getDebtorCardId());
        map.put("debtorName", debtorInfo.getDebtorName());
        map.put("debtorCasePhone", caseVo.getDebtorPhone());
        map.put("batchNumber", caseVo.getBatchNumber());
        map.put("projectCode", caseVo.getProjectCode());
        debtorInfoVoList.add(new GzxDebtorInfoVo(JSONUtil.toJsonStr(map), "", ":", "", ":", ""));
        return debtorInfoVoList;
    }

    /**
     * 修改欠款人信息
     *
     * @param debtorInfoBo
     */
    @Override
    public void updateDebtorInfo(GzxDebtorInfoEditBo debtorInfoBo) {
        GzxDebtorInfo debtorInfo = MapstructUtils.convert(debtorInfoBo, GzxDebtorInfo.class);
        debtorInfoMapper.updateById(debtorInfo);
    }

    /**
     * 获取明文数据
     *
     * @param type 明文类型
     * @param id   主键
     * @return
     */
    @Override
    public String getPlaintextById(String type, Long id) {
        GzxDebtorInfo debtorInfo = debtorInfoMapper.selectById(id);
        switch (type) {
            case "ADDRESS":
                return debtorInfo.getDebtorAddress();
            case "NOW_ADDRESS":
                return debtorInfo.getDebtorNowAddress();
            case "CARD_ID":
                return debtorInfo.getDebtorCardId();
            default:
                return "";
        }
    }

    /**
     * 批量新增欠款人
     *
     * @param debtorInfoList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(List<GzxDebtorInfo> debtorInfoList) {
        String currDate = CommonDateUtil.getCurrentTimeStr();
        List<List<GzxDebtorInfo>> batchList = Lists.partition(debtorInfoList, IntConstant.VALUE_1000);
        for (List<GzxDebtorInfo> batch : batchList) {
            String batchSql = batch.stream()
                    .map(s -> String.format("('%s', '%s', '%s', '%s','%s','%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                            escapeSql(s.getProjectCode()),
                            escapeSql(s.getDebtorName()),
                            escapeSql(String.valueOf(s.getDebtorSex())),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getDebtorPhone())),
                            escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getDebtorCardId())),
                            escapeSql(s.getDebtorBirth()),
                            escapeSql(String.valueOf(s.getDebtorAge())),
                            escapeSql(s.getDebtorProvince()),
                            escapeSql(s.getDebtorCity()),
                            escapeSql(s.getDebtorAddress()),
                            escapeSql(s.getDebtorNowAddress()),
                            escapeSql(String.valueOf(s.getDebtorAccountBalance())),
                            escapeSql(s.getTenantId()),
                            escapeSql(s.getCreateUser()),
                            escapeSql(currDate)
                    ))
                    .collect(Collectors.joining(", "));
            debtorInfoMapper.insertBatchIgnoreBySql(batchSql.replace("'null'", "null"));
            CommonSleepUtil.sleep100();
        }
    }
}
